from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from tadmin.models import AdminUser
from tadmin.ser import AdminUserSer
from tadmin.models import AdminUser, Roles, Resources
from tadmin.ser import adMinSer, ResourcesSer, RoleResourceSer
from tadmin.models import Resources
from tadmin.ser import ResourcesSer


# Create your views here.
class adAPIVIEW(APIView):
    def get(self, request):
        name = Roles.objects.all().order_by("id")
        ser = adMinSer(name, many=True)
        return Response(ser.data)


class All(APIView):
    def get(self, request):
        name = Resources.objects.filter(parent=None)
        ser = ResourcesSer(name, many=True)
        return Response(ser.data)


class AdminUserView(ModelViewSet):
    queryset = AdminUser.objects.all()
    serializer_class = AdminUserSer
class AllBY(APIView):
    def get(self, request):
        name = Resources.objects.filter(parent=request.query_params.get("id"))
        ser = ResourcesSer(name, many=True)
        return Response(ser.data)


class AddAPI(APIView):
    def post(self, request):
        name = request.data.get("role_name")
        cc = Roles.objects.filter(role_name=name).first()
        id = request.query_params.getlist("checked")
        print(id)
        if cc:
            for i in id:
                aa = i.split(",")
                for j in aa:
                    ser = RoleResourceSer(data={"role": cc.id, "resource": j})
                    print(cc.id)
                    if ser.is_valid():
                        ser.save()
                        return Response({"msg": "权限添加成功", "code": 200})
                    else:
                        return Response({"msg": ser.errors})

        ser = adMinSer(data=request.data)
        if ser.is_valid():
            ser.save()
            for i in id:
                aa = i.split(",")
                for j in aa:
                    ser = RoleResourceSer(data={"role": ser.data.id, "resource": j})
                    if ser.is_valid():
                        ser.save()
                        return Response({"msg": "添加成功", "code": 200})
                    else:
                        return Response({"msg": ser.errors})

# 展示所有资源管理项
class ResourcesAll(APIView):
    def get(self,request):
        resources = Resources.objects.all()
        ser = ResourcesSer(resources,many=True)
        return Response({"data":ser.data[1:]})
class ResourcesAdd(APIView):
    def post(self,request):
        print(request.data)
        ser = ResourcesSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code":200,"msg":"添加成功"})
        else:
            return Response({"code":400,"msg":ser.errors})